//
//  MSTabBarViewController.swift
//  SwiftWeibo
//
//  Created by 牟松 on 16/8/1.
//  Copyright © 2016年 DoNews. All rights reserved.
//

import UIKit

private let versionFileName = "version.json"

class MSTabBarViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildController()
        
        setupCompuseButton()
        
        setupNewFature()

    }
    
    override func viewWillAppear(_ animated: Bool) {
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin(notifiction:)), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    // MARK: - 添加监听方法
    
    // @objc的作用是让该方法具有OC语言的属性，可以在运行时被发送消息
    @objc private func compuseButtonDidClick(){
        print("写微博")
    }
    
    // 弹出用户登录界面
    @objc private func userLogin(notifiction: Notification) {
        print(notifiction)
        
        let OAuthViewController = UINavigationController(rootViewController: MSOAuthViewController())
        
        present(OAuthViewController, animated: true, completion: nil)
        
    }
    
    // MARK: - 私有控件
    private lazy var compuseButton : UIButton = UIButton(MS_Button: nil, imageName: "tabbar_compose_icon_add", selectedImageName: "tabbar_compose_icon_add_highlighted", backgroundImageNmae: "tabbar_compose_button", selectedBackgroundImageName: "tabbar_compose_button_highlighted")

    
}

// MARK: - 设置新特性
extension MSTabBarViewController{
    private func setupNewFature(){
        
        if !MSUserAccountInfoModel.shared.userLogin {
            return
        }
        
        // 判断版本
        print("Bundle.main.infoDictionary =========\(Bundle.main.infoDictionary)")
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        
        let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let versionFilePath = (documentPath as NSString).appendingPathComponent(versionFileName)
        let versionString = try? String(contentsOfFile: versionFilePath)
        
        try? currentVersion.write(toFile: versionFilePath, atomically: true, encoding: .utf8)
        
        let v = currentVersion != versionString ? MSNewFeatureView.newFeatureView() : MSWelcomeView.welcomeView()
                
        view.addSubview(v)
    
        
    }
}

// MARK: - 设置tabbar
extension MSTabBarViewController{
    
    // MARK: - 设置tabbar中间写微博的button
    private func setupCompuseButton(){
        tabBar.addSubview(compuseButton)
        
        let childViewControllerNumber = CGFloat(childViewControllers.count)
        let compuseButtonWidet = tabBar.bounds.size.width / childViewControllerNumber - 1
        
        compuseButton.frame = tabBar.bounds.insetBy(dx: compuseButtonWidet * 2, dy: 0)
        
        compuseButton.addTarget(self, action: #selector(compuseButtonDidClick), for: .touchUpInside)
    
    }
    
    // MARK: - 设置子控制器
    private func setupChildController(){
        
        var viewCotrollersArray = [UIViewController]()
        
//        let array = [["className": "MSHomeViewController", "title": "首页", "imageName": "tabbar_home", "selectedImageName": "tabbar_home_selected", "visitorView": ["VCName": "MSHomeViewController", "smallLabelText": "关注一些人，回这里看看有什么惊喜"]],
//                     ["className": "MSMessageViewController", "title": "消息", "imageName": "tabbar_message_center", "selectedImageName": "tabbar_message_center_selected", "visitorView": ["VCName": "MSMessageViewController", "smallLabelText": "登录后，别人评论你的微博，给你发消息，都会在这里收到通知"]],
//                     ["className": "compuseButton", "title": "消息", "imageName": "tabbar_message_center", "selectedImageName": "tabbar_message_center_selected", "visitorView": ["VCName": "MSHomeViewController", "smallLabelText": "关注一些人，回这里看看有什么惊喜"]],
//                     ["className": "MSDiscoverViewController", "title": "发现", "imageName": "tabbar_discover", "selectedImageName": "tabbar_discover_selected", "visitorView": ["VCName": "MSDiscoverViewController", "smallLabelText": "关注一些人，回这里看看有什么惊喜"]],
//                     ["className": "MSProfileViewController", "title": "我", "imageName": "tabbar_profile", "selectedImageName": "tabbar_profile_selected", "visitorView": ["VCName": "MSProfileViewController", "smallLabelText": "登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]]
//        ]
     
        // 将数组写成json文件
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        (data as NSData).write(toFile: "/Users/musong/Desktop/main.json", atomically: true)
        
        let path = Bundle.main.path(forResource: "main.json", ofType: nil)
        let data = NSData(contentsOfFile: path!)
        
        guard let array = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as! [[String : AnyObject]] else {
            return
        }

        for dict in array {
            
            viewCotrollersArray.append(createController(dict: dict))
        }
        
        viewControllers = viewCotrollersArray
    
        
    }
    // 根据一个字典，运用映射机制创建控制器 [className, title, imageName]
    private func createController(dict: [String: AnyObject]) -> UIViewController {
        guard let className = dict["className"],
            let title = dict["title"],
            let imageName = dict["imageName"],
            let selectedImage = dict["selectedImageName"],
            let VC = NSClassFromString(Bundle.main.namespace + "." + (className as! String)) as? MSBaseViewController.Type, // 根据字典获取VC
        let visitorDic: [String: String] = dict["visitorView"] as? [String: String]
        
        else {
            return MSBaseViewController()
        }
        
//        print(Bundle.main.namespace + "." + className)
        
        let VC1 = VC.init()
        VC1.setVisiterDic = visitorDic
        
        VC1.title = title as? String
        
        // 设置图片
        VC1.tabBarItem.image = UIImage(named: imageName as! String)
        VC1.tabBarItem.selectedImage = UIImage(named: selectedImage as! String)?.withRenderingMode(.alwaysOriginal)
        
        // 设置字体
        VC1.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: #colorLiteral(red: 0.9921568627, green: 0.5333333333, blue: 0.168627451, alpha: 1)], for: .highlighted)
        
        // 添加中间按钮
        
        let mainNav = MSNavViewController(rootViewController: VC1)
        
        return mainNav
        
        
        
    }
}
